package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store-master/models"
)

type ShopController struct {
	beego.Controller
}

type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	address := c.GetString("address")
	area := c.GetString("area")
	types := c.GetString("types")
	shop := models.Shop{
		Name:    name,
		Address: address,
		Area:    area,
		Types:   types,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "添加成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}

func (c *ShopController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	address := c.GetString("address")
	area := c.GetString("area")
	types := c.GetString("types")
	shop := models.Shop{
		Name:    name,
		Address: address,
		Area:    area,
		Types:   types,
	}
	err := models.DB.Where("id=?", id).Updates(&shop).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "修改成功",
		Data: shop,
	}
	c.ServeJSON()
	return
}

func (c *ShopController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	f := (page - 1) * size
	var count int64
	var shop []models.Shop
	query := models.DB.Model(&models.Shop{})
	query.Offset(f).Limit(size).Find(&shop)
	query.Count(&count)
	lyz := make(map[string]interface{})
	lyz["count"] = count
	lyz["shop"] = shop
	c.Data["json"] = Res{
		Code: 200,
		Msg:  "查询成功",
		Data: lyz,
	}
	c.ServeJSON()
	return
}
